package bar.dark.lee.fan;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.select.SelectData;

public class FanInInfoActivity extends SuperActivity
{
	/** 정보에서 보내는 데이터 구조 */
	public static final String FAN_INFO_DATA = "fanInfoData";
	
	public final String CHECK_OK = "갚음";
	public final String CHECK_NO = "못갚음";
	public final String CHECK_NOOK = "덜갚음";
	
	private DBSQLite sql;
	
	/** 타입 텍스트 뷰 */
	private TextView typeText;
	
	/** 통장이나 카드 종류 뷰*/
	private View kindView;
	/** 종류 이름 텍스트 뷰 */
	private TextView kind;
	/** 통장이나 카드 종류 텍스트 뷰*/
	private TextView kindText;
	
	/** 이름 텍스트 뷰 */
	private TextView nameText;
	
	/** 날짜 텍스트 뷰*/
	private TextView dateText;
	
	/** 받을돈 타이틀 뷰 */
	private TextView moneyTitle;
	/** 빌린돈 텍스트 뷰 */
	private TextView moneyText;
	
	/** 받을돈 타이틀 뷰 */
	private TextView moneyTitle2;
	/** 받을돈 텍스트 뷰 */
	private TextView moneyText2;
	
	/** 남은 돈 텍스트 뷰 */
	private TextView moneyText3;
	
	/** 전화번호 버튼 뷰 */
	private View telView;
	/** 전화번호 텍스트 뷰 */
	private TextView telText;
	
	/** 해결유무 텍스트 뷰*/
	private TextView checkSignText;
	
	/** 내용 텍스트 뷰 */
	private TextView memoText;
	
	/** 삭제 버튼 */
	private Button deleteButton;
	/** 수정 버튼 */
	private Button updateButton;
	/** 받음 버튼 */
	private Button checkButton;
	
	private View alertView;
	private TextView alertTextView;
	
	private FanData data = null;
	
	private int deleteYn;
	
	private BigDecimal myOutMoney = BigDecimal.ZERO;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setGoneTipButton();
		
		setTitle("빌린금액 정보");
		
		Intent intent = getIntent();
		
		data = intent.getParcelableExtra(FanInActivity.FAN_IN_DATA);
		
		setContentView(R.layout.fan_out_info_activity);
		
		setFindView();
		setOnClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}

	private void setFindView()
	{
		typeText = (TextView) findViewById(R.id.fanOutInfoType);
		kindView = findViewById(R.id.fanOutInfoKindView);
		kind = (TextView) findViewById(R.id.fanOutInfoKind);
		kindText = (TextView) findViewById(R.id.fanOutInfoKindText);
		nameText = (TextView) findViewById(R.id.fanOutInfoName);
		dateText = (TextView) findViewById(R.id.fanOutInfoDate);
		moneyTitle = (TextView) findViewById(R.id.fanOutInfoMoneyText);
		moneyTitle.setText("빌린돈");
		moneyTitle2 = (TextView) findViewById(R.id.fanOutInfoMoneyText2);
		moneyTitle2.setText("갚은돈");
		
		moneyText = (TextView) findViewById(R.id.fanOutInfoMoney);
		moneyText2 = (TextView) findViewById(R.id.fanOutInfoMoney2);
		
		moneyText3 = (TextView) findViewById(R.id.fanOutInfoMoney3);
		
		telView = findViewById(R.id.fanOutInfoTelView);
		telText = (TextView) findViewById(R.id.fanOutInfoTel);
		checkSignText = (TextView) findViewById(R.id.fanOutInfoCheckSign);
		memoText = (TextView) findViewById(R.id.fanOutInfoMemo);
		
		deleteButton = (Button) findViewById(R.id.fanOutInfoDeleteButton);
		updateButton = (Button) findViewById(R.id.fanOutInfoUpdateButton);
		checkButton = (Button) findViewById(R.id.fanOutInfoCheckButton);
		checkButton.setText("갚음");
		
		alertView = (View) findViewById(R.id.fanOutInfo_viewAlert);
		alertTextView = (TextView) findViewById(R.id.fanOutInfo_textAlert);
	}
	
	private void setData()
	{
		if (data != null)
		{
			sql.selectMapTile(this, "SELECT * FROM fan_in WHERE id = " 
					 + data.getId() + ";", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int id = c.getColumnIndex("id");
					int type = c.getColumnIndex("type");
					int name = c.getColumnIndex("name");
					int date = c.getColumnIndex("date");
					int money = c.getColumnIndex("money");
					int tel = c.getColumnIndex("tel");
					int moneyname = c.getColumnIndex("moneyname");
					int checkSign = c.getColumnIndex("checksign");
					int linkId = c.getColumnIndex("linkid");
					int checkId = c.getColumnIndex("checkid");
					int memo = c.getColumnIndex("memo");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						data = new FanData();
						
						data.setId(c.getInt(id) + "");
						data.setType(c.getInt(type) + "");
						data.setName(c.getString(name));
						data.setDate(c.getInt(date) + "");
						data.setMoney(c.getString(money));
						data.setTel(c.getString(tel));
						data.setMoneyname(c.getString(moneyname));
						data.setCheckSign(c.getInt(checkSign) + "");
						data.setLinkId(c.getInt(linkId) + "");
						data.setCheckId(c.getInt(checkId) + "");
						data.setMemo(c.getString(memo));
						
						c.moveToNext();
					}
				}
			});
		}
		
		sql.selectMapTile(this, "SELECT deleteyn FROM in_out WHERE id = "
				+ data.getLinkId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int deleteynIdx = c.getColumnIndex("deleteyn");
				
				deleteYn = 0;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					deleteYn = c.getInt(deleteynIdx);
					c.moveToNext();
				}
			}
		});
	}

	private void setInfoData()
	{
		// 타입
		if (data.getType().equals(BDConstents.BANK_TYPE))
		{
			typeText.setText(BDConstents.BANK_MONEY);
			kindView.setVisibility(View.VISIBLE);
			kindText.setText(data.getMoneyname());
			kind.setText("통장");
		}
		else
		{
			typeText.setText(BDConstents.REAL_MONEY);
			kindView.setVisibility(View.GONE);
		}
		
		// 이름
		nameText.setText(data.getName());
		
		// 날짜
		dateText.setText(BDUtil.getDateButton(data.getDate()));
		
		// 빌린 돈
		moneyText.setText(BDUtil.getWon(data.getMoney()) + shape);
		
		// 갚은 돈
		sql.selectMapTile(this, "SELECT outmoney, postmoney FROM in_out WHERE linkid = "
				+ data.getId() + " and category = '"
				+ BDConstents.CATEGORY_FAN_IN_CHECK + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int outmoney = c.getColumnIndex("outmoney");
				int postmoney = c.getColumnIndex("postmoney");
				
				myOutMoney = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					myOutMoney = myOutMoney.add(new BigDecimal(c.getString(outmoney)));
					myOutMoney = myOutMoney.add(new BigDecimal(c.getString(postmoney)));
					c.moveToNext();
				}
				
				moneyText2.setText(BDUtil.getWon(myOutMoney + "") + shape);
			}
		});
		
		moneyText3.setText(BDUtil.getWon(
				new BigDecimal(data.getMoney()).subtract(myOutMoney).toString()) + shape);
		
		// 전화번호
		telText.setText(data.getTel());
		
		// 해결유무
		HashMap<String, String> map = new HashMap<String, String>();
		switch (new BigDecimal(data.getMoney()).compareTo(new BigDecimal(myOutMoney+""))) {
			case -1:
				map.put("checksign", "1");
				data.setCheckSign("1");
				break;
			case 0:
				map.put("checksign", "1");
				data.setCheckSign("1");
				break;
			case 1:
				if (new BigDecimal(myOutMoney+"").compareTo(BigDecimal.ZERO) == 1)
				{
					map.put("checksign", "2");
					data.setCheckSign("2");
				}
				else
				{
					map.put("checksign", "0");
					data.setCheckSign("0");
				}
				break;
			default:
				break;
		}
		String[] whereArgs = new String[]{data.getId()};
		sql.update(FanInInfoActivity.this, "fan_in", map, "id = ?", whereArgs);
		
		// 해결 유무
		if (data.getCheckSign().equals("0"))
		{
			checkSignText.setText(CHECK_NO);
			checkSignText.setTextColor(Color.RED);
			checkButton.setVisibility(View.VISIBLE);
		}
		else if (data.getCheckSign().equals("1"))
		{
			checkSignText.setText(CHECK_OK);
			checkSignText.setTextColor(getResources().getColor(R.color.inmoney));
			checkButton.setVisibility(View.VISIBLE);
		}
		else
		{
			checkSignText.setText(CHECK_NOOK);
			checkSignText.setTextColor(getResources().getColor(R.color.postmoney));
			checkButton.setVisibility(View.VISIBLE);
		}
		
		// 메모
		memoText.setText(data.getMemo());
		
		// 통장이나 카드가 삭제된 여뷰에 따라서 수정 삭제 가능할지 여부
		if (deleteYn == 0)
		{
			deleteButton.setVisibility(View.VISIBLE);
			updateButton.setVisibility(View.VISIBLE);
		}
		else
		{
			updateButton.setVisibility(View.GONE);
			checkButton.setVisibility(View.GONE);
			
			alertView.setVisibility(View.VISIBLE);
			
			deleteButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					new ShowDialog().execute(BDUtil.asyncFlag, 2);
				}
			});
		}
	}
	
	private void setOnClickListener()
	{
		telView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				AlertDialog.Builder dialog = new AlertDialog.Builder(FanInInfoActivity.this);
				
				View view = getLayoutInflater().inflate(R.layout.view_send_dialog, null);
				
				View telView = view.findViewById(R.id.sendDialogTelView);
				View smsView = view.findViewById(R.id.sendDialogSmsView);
				
				dialog.setView(view);
				
				telView.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						// Intent.ACTION_CALL 전화 바로 걸기.
						// Intent.ACTION_DIAL 전화 걸기 화면으로 이동.
						
						Intent intent = new Intent(
								Intent.ACTION_DIAL, Uri.parse("tel:" + telText.getText().toString()));
						startActivity(intent);
					}
				});
				
				smsView.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.putExtra("address", telText.getText().toString()); // 받는사람 번호
						intent.setType("vnd.android-dir/mms-sms");
						startActivity(intent);
					}
				});
				
				dialog.show();
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setDeleteData();
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(FanInInfoActivity.this, FanInInsertActivity.class);
				intent.putExtra(FanInInsertActivity.FLAG, FanInInsertActivity.UPDATE);
				intent.putExtra(FAN_INFO_DATA, data);
				startActivity(intent);
			}
		});
		
		checkButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(FanInInfoActivity.this, FanOutInsertActivity.class);
				intent.putExtra(FanOutInsertActivity.INSERT_FLAG, FanOutInsertActivity.CHECK);
				intent.putExtra(FAN_INFO_DATA, data);
				startActivity(intent);
			}
		});
	}
	
	/**
	 * fan_out 과 in_out 에 있는 내용을 전부다 지운다.
	 */
	private void setDeleteData()
	{
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("경고");
		dialog.setIcon(android.R.drawable.ic_delete);
		dialog.setMessage("삭제 하실 경우 가계부의 내역도 삭제 됩니다. 삭제 하시겠습니까?");
		dialog.setPositiveButton("삭제", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
				dialog.dismiss();
			}
		});
		
		dialog.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		
		dialog.show();
	}
	
	/**
	 * 데이터를 삭제 하고 롤백한다.
	 */
	private void setFanInInfoDeleteData()
	{
		setDeleteInOutTable();
		
		// fan_out 테이블 내용을 삭제한다.
		String [] whereArgs = new String[]{data.getId()};
		sql.delete(FanInInfoActivity.this, "fan_in", "id = ?", whereArgs);
	}

	/**
	 * in_out 테이블 내용을 삭제한다.
	 */
	private void setDeleteInOutTable()
	{
		setDeleteIn();
		
//		// 해결 됬을 경우 해결 된것도 롤백 시킨다.
//		if (data.getCheckSign().equals("1"))
//		{
//			setDeleteOut();
//		}
	}

	private ArrayList<SelectData> idList;
	private void setDeleteIn()
	{
		idList = new ArrayList<SelectData>();
		
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE linkid = "
				+ data.getId() + " and type = '" + BDConstents.FAN_TYPE 
				+ "' and category = '"
				+ BDConstents.CATEGORY_FAN_IN_CHECK + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				SelectData data = null;
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data = new SelectData();
					data.setId(c.getInt(id) + "");
					data.setCategory(c.getString(category));
					data.setMemo(c.getString(memo));
					data.setInMoney(c.getString(inmoney));
					data.setOutMoney(c.getString(outmoney));
					data.setPostMoney(c.getString(postmoney));
					data.setDate(c.getInt(date) + "");
					data.setMoneyKind(c.getString(moneykind));
					data.setType(c.getInt(type) + "");
					data.setLinkId(c.getInt(linkid) + "");
					data.setLinktype(c.getInt(linktype) + "");
					idList.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		// 갚은 금액들을 롤백한다.
		for (int i = 0; i < idList.size(); i++)
		{
			SelectData data = idList.get(i);
			
			if (data != null)
			{
				if (deleteYn == 1)
				{
					setDeleteRealTable(data.getId(), data.getOutMoney(), 1);
				}
				else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
				{
					setDeleteCreditTable(data);
				}
				else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
				{
					setDeleteCheckTable(data, 1);
				}
				else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
				{
					setDeleteBankBookTable(data, -1, 1, 1);
				}
				else if (data.getLinktype().equals(BDConstents.REAL_TYPE))
				{
					setDeleteRealTable(data.getId(), data.getOutMoney(), 1);
				}
			}
		}
		
		// 갚은 금액을 삭제한다.
		for (int i=0; i < idList.size(); i++)
		{
			SelectData data = idList.get(i);
			
			String [] whereArgs = new String[]{data.getId()};
			sql.delete(this, "in_out", "id = ?", whereArgs);
		}
		
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = "
				+ data.getLinkId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				SelectData data = null;
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data = new SelectData();
					data.setId(c.getInt(id) + "");
					data.setCategory(c.getString(category));
					data.setMemo(c.getString(memo));
					data.setInMoney(c.getString(inmoney));
					data.setOutMoney(c.getString(outmoney));
					data.setPostMoney(c.getString(postmoney));
					data.setDate(c.getInt(date) + "");
					data.setMoneyKind(c.getString(moneykind));
					data.setType(c.getInt(type) + "");
					data.setLinkId(c.getInt(linkid) + "");
					data.setLinktype(c.getInt(linktype) + "");
				}
				
				if (data != null)
				{
					if (deleteYn == 1)
					{
						setDeleteRealTable(data.getId(), data.getInMoney(), 0);
					}
					else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
					{
						setDeleteCreditTable(data);
					}
					else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
					{
						int bankId = getBankBookId(data.getMoneyKind());
						
						setDeleteBankBookTable(data, bankId, 0, 1);
					}
					else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
					{
						setDeleteCheckTable(data, 0);
					}
					else
					{
						setDeleteRealTable(data.getId(), data.getInMoney(), 0);
					}
				}
			}
		});
		
		String [] whereArgs = new String[]{data.getLinkId()};
		sql.delete(this, "in_out", "id = ?", whereArgs);
	}
	
	/**
	 * 통장 아이디 리턴
	 */
	private int bankId;
	private int getBankBookId(String name)
	{
		sql.selectMapTile(this, "SELECT * FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(name) + "';", new ParseSelectData() {
			@Override
			public void resultData(Cursor c) {
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					bankId = c.getInt(c.getColumnIndex("id"));
				}
			}
		});
		
		return bankId; 
	}
	
	private void setDeleteOut()
	{
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = "
				+ data.getCheckId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				SelectData data = null;
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data = new SelectData();
					data.setId(c.getInt(id) + "");
					data.setCategory(c.getString(category));
					data.setMemo(c.getString(memo));
					data.setInMoney(c.getString(inmoney));
					data.setOutMoney(c.getString(outmoney));
					data.setPostMoney(c.getString(postmoney));
					data.setDate(c.getInt(date) + "");
					data.setMoneyKind(c.getString(moneykind));
					data.setType(c.getInt(type) + "");
					data.setLinkId(c.getInt(linkid) + "");
					data.setLinktype(c.getInt(linktype) + "");
				}
				
				if (data != null)
				{
					if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
					{
						setDeleteCreditTable(data);
					}
					else
					{
						if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
						{
							setDeleteCheckTable(data, 1);
						}
						else
						{
							setDeleteRealTable(data.getId(), data.getOutMoney(), 1);
						}
					}
				}
			}
		});
		
		String [] whereArgs = new String[]{data.getCheckId()};
		sql.delete(this, "in_out", "id = ?", whereArgs);
	}
	
	/**
	 * 체크카드 테이블을 롤백시킨다.
	 * @param data
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 */
	private void setDeleteCheckTable(final SelectData data, final int flag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int banklinkIdx = c.getColumnIndex("banklink");
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(banklinkIdx);
					c.moveToNext();
				}
				
				setDeleteBankBookTable(data, id, flag, 0);
			}
		});
	}
	
	/**
	 * 통장 테이블을 롤백 시킨다.
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 * @param id 
	 * @param data 
	 * @param bankCheckFlag 0 = 체크카드, 1 = 통장
	 */
	private void setDeleteBankBookTable(final SelectData data, final int id, final int flag, final int checkFlag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		String sqlQurey = "";
		
		if (id == -1)
		{
			sqlQurey = "SELECT money FROM bankbook WHERE name = '" + BDUtil.getApostrophe(data.getMoneyKind()) + "';";
		}
		else
		{
			sqlQurey = "SELECT money FROM bankbook WHERE id = " + id + ";";
		}
		
		sql.selectMapTile(this, sqlQurey, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(BDUtil.getCommaDel(c.getString(moneyIdx))));
					c.moveToNext();
				}
				
				int balanceFlag = 0;
				String rollMoney = "0";
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(data.getInMoney()));
					balanceFlag = 0;
					rollMoney = data.getInMoney();
				}
				else
				{
					money = money.add(new BigDecimal(data.getOutMoney()));
					balanceFlag = 1;
					rollMoney = data.getOutMoney();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = null;
				
				if (id == -1)
				{
					whereArgs = new String[]{data.getMoneyKind()};
					sql.update(FanInInfoActivity.this, 
							"bankbook", map, "name = ?", whereArgs);
				}
				else
				{
					whereArgs = new String[]{id + ""};
					sql.update(FanInInfoActivity.this, 
							"bankbook", map, "id = ?", whereArgs);
				}
				
				String type = BDConstents.BANK_TYPE;
				
				if (checkFlag == 0)
				{
					type = BDConstents.CHECK_TYPE;
				}
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), type, 
						data.getMoneyKind(), rollMoney.toString(), balanceFlag);
				
			}
		});
	}
	
	/**
	 * 현금 테이블을 롤백 시킨다.
	 * @param id
	 * @param data
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 */
	private void setDeleteRealTable(final String id, final String realmoney, final int flag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT money FROM real_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				int balanceFlag = 0;
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(realmoney));
					balanceFlag = 0;
				}
				else
				{
					money = money.add(new BigDecimal(realmoney));
					balanceFlag = 1;
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				sql.update(FanInInfoActivity.this, "real_money", map, null, null);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(id, BDConstents.REAL_TYPE, 
						BDConstents.REAL_MONEY, realmoney.toString(), balanceFlag);
			}
		});
	}
	
	/**
	 * 신용카드 테이블을 롤백시킨다.
	 * @param data 
	 */
	private void setDeleteCreditTable(final SelectData data)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int outmoneyIdx = c.getColumnIndex("outmoney");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(outmoneyIdx)));
					c.moveToNext();
				}
				
				money = money.subtract(new BigDecimal(data.getPostMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{data.getMoneyKind()}; 
				
				sql.update(FanInInfoActivity.this, "credit_card", map, "name = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.CREDIT_TYPE, 
						data.getMoneyKind(), data.getPostMoney(), 0);
			}
		});
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(FanInInfoActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) {
				if (arg0[1] == 1)
				{
					setData();
					
					return arg0[1];
				}
				else if (arg0[1] == 2) 
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setFanInInfoDeleteData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				setInfoData();
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(FanInInfoActivity.this, "알림", 
						BDConstents.CATEGORY_FAN_OUT_MONEY + "이 삭제 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
